package com.gxnu.edu.cn.client.controller;

import com.gxnu.edu.cn.ttxxt.entity.ChatGroups;
import com.gxnu.edu.cn.ttxxt.entity.GroupsMembers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.HttpStatusCodeException;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

@Component
public class GroupClient {
    @Autowired
    private RestTemplate restTemplate;

    private String baseUrl = "http://localhost:8080";

    public CompletableFuture<ChatGroups> createGroup(Map<String, String> request) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                ResponseEntity<ChatGroups> response = restTemplate.postForEntity(
                        baseUrl + "/api/groups/",
                        request,
                        ChatGroups.class
                );
                return response.getBody();
            } catch (Exception e) {
                throw new RuntimeException("创建群组失败: " + e.getMessage(), e);
            }
        });
    }

    public CompletableFuture<Map<String, Object>> addMember(Long groupId, Map<String, Long> request) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                ResponseEntity<Map> response = restTemplate.postForEntity(
                        baseUrl + "/api/groups/" + groupId + "/members",
                        request,
                        Map.class
                );
                return response.getBody();
            } catch (Exception e) {
                throw new RuntimeException("添加成员失败: " + e.getMessage(), e);
            }
        });
    }

    public CompletableFuture<Map<String, Object>> removeMember(Long groupId, Long userId) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                ResponseEntity<Map> response = restTemplate.exchange(
                        baseUrl + "/api/groups/" + groupId + "/members/" + userId,
                        HttpMethod.DELETE,
                        null,
                        Map.class
                );
                return response.getBody();
            } catch (Exception e) {
                throw new RuntimeException("移除成员失败: " + e.getMessage(), e);
            }
        });
    }

    public CompletableFuture<Map<String, Object>> updateMemberRole(Long groupId, Long userId, Map<String, Integer> request) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                ResponseEntity<Map> response = restTemplate.exchange(
                        baseUrl + "/api/groups/" + groupId + "/members/" + userId + "/role",
                        HttpMethod.PUT,
                        new HttpEntity<>(request),
                        Map.class
                );
                return response.getBody();
            } catch (Exception e) {
                throw new RuntimeException("更新成员角色失败: " + e.getMessage(), e);
            }
        });
    }

    public CompletableFuture<Map<String, Object>> dissolveGroup(Long groupId, Long operatorId) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                // 1. 设置请求头（明确JSON格式）
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON);

                // 2. 构建请求体（包含两个参数）
                Map<String, Long> requestBody = new HashMap<>();
                requestBody.put("groupId", groupId);      // 显式添加groupId
                requestBody.put("operatorId", operatorId); // 显式添加operatorId

                HttpEntity<Map<String, Long>> entity = new HttpEntity<>(requestBody, headers);

                // 3. 发送DELETE请求（使用exchange确保参数正确传递）
                ResponseEntity<Map<String, Object>> response = restTemplate.exchange(
                        baseUrl + "/api/groups/" + groupId,  // 路径参数groupId
                        HttpMethod.DELETE,
                        entity,
                        new ParameterizedTypeReference<Map<String, Object>>() {}
                );

                // 4. 处理响应
                if (response.getStatusCode().is2xxSuccessful()) {
                    return response.getBody();
                } else {
                    throw new RuntimeException("解散群组失败，状态码: " + response.getStatusCodeValue());
                }
            } catch (HttpStatusCodeException e) {
                throw new RuntimeException("解散群组失败，状态码: " +
                        ", 错误信息: " + e.getResponseBodyAsString(), e);
            } catch (Exception e) {
                throw new RuntimeException("解散群组异常: " + e.getMessage(), e);
            }
        });
    }


    public CompletableFuture<List<ChatGroups>> getUserGroups(Long userId) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                ResponseEntity<List<ChatGroups>> response = restTemplate.exchange(
                        baseUrl + "/api/groups/user/" + userId,
                        HttpMethod.GET,
                        null,
                        new ParameterizedTypeReference<List<ChatGroups>>() {}
                );
                return response.getBody();
            } catch (Exception e) {
                throw new RuntimeException("获取用户群组失败: " + e.getMessage(), e);
            }
        });
    }

    public CompletableFuture<List<ChatGroups>> getUserJoinGroups(Long userId) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                ResponseEntity<List<ChatGroups>> response = restTemplate.exchange(
                        baseUrl + "/api/groups/userjoin/" + userId,
                        HttpMethod.GET,
                        null,
                        new ParameterizedTypeReference<List<ChatGroups>>() {}
                );
                return response.getBody();
            } catch (Exception e) {
                throw new RuntimeException("获取用户群组失败: " + e.getMessage(), e);
            }
        });
    }


    // 新增：申请加入群组
    public CompletableFuture<Map<String, Object>> applyToJoinGroup(Map<String, Object> request) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON);
                headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
                headers.setAcceptCharset(Collections.singletonList(StandardCharsets.UTF_8));

                // 修正泛型类型，与 request 保持一致
                HttpEntity<Map<String, Object>> entity = new HttpEntity<>(request, headers);

                ResponseEntity<Map> response = restTemplate.postForEntity(
                        baseUrl + "/api/groups/apply",
                        entity,  // 传递正确的 entity 对象
                        Map.class
                );
                return response.getBody();
            } catch (Exception e) {
                throw new RuntimeException("申请加入群组失败: " + e.getMessage(), e);
            }
        });
    }

    public CompletableFuture<Map<String, Object>> inviteToGroup(Map<String, Long> request) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                String url = baseUrl + "/api/groups/" + request.get("groupId") + "/members";

                // 创建请求头，明确指定字符编码
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON);

                // 修改请求体，确保包含 userId 和 role
                Map<String, Long> requestBody = new HashMap<>();
                requestBody.put("userId", request.get("friendId"));
                requestBody.put("role", 1L); // 假设普通成员的角色为 0

                // 创建 HttpEntity 对象，包含请求头和请求体
                HttpEntity<Map<String, Long>> entity = new HttpEntity<>(requestBody, headers);

                // 使用 exchange 方法代替 postForEntity，以便可以设置请求头
                ResponseEntity<Map<String, Object>> response = restTemplate.exchange(
                        url,
                        HttpMethod.POST,
                        entity,
                        new ParameterizedTypeReference<Map<String, Object>>() {}
                );

                return response.getBody();
            } catch (HttpStatusCodeException e) {
                // 处理 HTTP 状态码异常，获取响应内容
                String responseBody = e.getResponseBodyAsString();
                throw new RuntimeException("邀请好友加入群组失败，HTTP状态码: " + e.getStatusCode() +
                        ", 响应内容: " + responseBody, e);
            } catch (Exception e) {
                throw new RuntimeException("邀请好友加入群组失败: " + e.getMessage(), e);
            }
        });
    }

    public CompletableFuture<List<GroupsMembers>> getGroupMembers(Long groupId) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                ResponseEntity<List<GroupsMembers>> response = restTemplate.exchange(
                        baseUrl + "/api/groups/" + groupId + "/members",
                        HttpMethod.GET,
                        null,
                        new ParameterizedTypeReference<List<GroupsMembers>>() {}
                );
                return response.getBody();
            } catch (Exception e) {
                throw new RuntimeException("获取群组成员失败: " + e.getMessage(), e);
            }
        });
    }

    public CompletableFuture<ChatGroups> getGroupInfo(Long groupId) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                ResponseEntity<ChatGroups> response = restTemplate.getForEntity(
                        baseUrl + "/api/groups/" + groupId,
                        ChatGroups.class
                );
                return response.getBody();
            } catch (Exception e) {
                throw new RuntimeException("获取群组信息失败: " + e.getMessage(), e);
            }
        });
    }

    public CompletableFuture<ChatGroups> getGroupByName(String groupName, Long operatorId) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                // 构造完整的URL，包括查询参数
                String url = baseUrl + "/api/groups/name?groupName=" + groupName + "&operatorId=" + operatorId;
                ResponseEntity<ChatGroups> response = restTemplate.getForEntity(
                        url,
                        ChatGroups.class
                );
                if (response.getStatusCode() == HttpStatus.OK) {
                    return response.getBody();
                } else {
                    throw new RuntimeException("获取群组信息失败，状态码: " + response.getStatusCodeValue());
                }
            } catch (Exception e) {
//                log.error("获取群组信息失败: ", e);
                throw new RuntimeException("获取群组信息失败: " + e.getMessage(), e);
            }
        });
    }
}